package cn.yuanqiao.web.controller.system;

import cn.yuanqiao.auth.util.TokenParamUtil;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.core.domain.entity.SysMenu;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import cn.yuanqiao.common.core.domain.model.LoginBody;
import cn.yuanqiao.common.service.SysPermissionService;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.framework.web.service.SysLoginService;
import cn.yuanqiao.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

import static cn.yuanqiao.activiti.listener.GlobalEventListener.logger;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/auth")
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private Environment environment;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public R<?> login(@RequestBody LoginBody loginBody)
    {

        // 生成令牌
        Map<String, Object> login = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), loginBody.getTenantCode(), loginBody.getUserType());

        return R.ok(login);
    }

    /**
     * 登录方法 恒泰
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login/htai")
    public R<?> login(@RequestParam("secret") String loginBody) {
        String hengtai_isSyncTask = environment.getProperty("HTORG.isSyncTask");
        if ("true".equalsIgnoreCase(hengtai_isSyncTask)) {
            byte[] decoded = Base64.getDecoder().decode(loginBody);
            String decodedStr = new String(decoded);
            String[] split = decodedStr.split("&");
            String taskId = "";
            Map<String, Object> login = new HashMap<>();
            for (String s : split) {
                String[] split1 = s.split("=");
                String key = split1[0];
                String val = split1[1];
                if ("createTime".equals(key)) {
                    long l = Long.valueOf(DateUtils.dateTime()) - Long.valueOf(val);
                    if (l > 30) {
                        return R.fail("链接已经过期!");
                    }
                }
                if ("assignee".equals(key)) {
                    login = loginService.loginhta(Long.valueOf(val));
                }
                if ("taskId".equals(key)) {
                    taskId = val;
                }
            }


            login.put("taskId", taskId);
            return R.ok(login);
        }
        return R.fail("请确认用户信息");
    }

    /**
     * 登录方法 农发单点登录
     *
     * @param ticketVal oa回传的标识
     * @return 结果
     */
    @PostMapping("/login/nfSignOn")
    public R<?> loginNF(@RequestParam("secret") String ticketVal) {
        if(!"".equals(ticketVal)&& ticketVal!=null){
            String oaPath = TokenParamUtil.getOAPath();
            String url = oaPath+"/seeyon/thirdpartyController.do?"+ticketVal;
            RestTemplate restTemplate = new RestTemplate();
            String loginBody = restTemplate.getForObject(url, String.class);
            //070241 康宁宁
            //String loginBody = "070241";
            try {
                loginBody = URLDecoder.decode(loginBody, "utf-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            logger.info("OA单点登录对接url::::::{}" + url+"  响应结果::::::{} " + loginBody);
            Map<String, Object> login = new HashMap<>();
            login = loginService.loginnf(loginBody);
            return R.ok(login);
        }else {
            return R.fail("oa单点登录失败，用户登录名为空");
        }
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    @PostMapping("/getSoloTenant")
    public R<?> getSoloTenant()
    {
        Map<String,Object> result = new HashMap<>();
        result.put("isSoloTenant", TokenParamUtil.isSoloTenant());
        result.put("soloTenantCode",TokenParamUtil.getDefaultTenant());
        return R.ok(result);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
